package net.suntec.mrs.client.message;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class FileMessageSender extends MessageSender {

	/** 文件路径 */
	private String filePath;

	private final static int BUFFER_SIZE = 2048;

	public FileMessageSender( String filePath, String userToken, final String host, final int port ) {
		super( userToken, host, port );
		this.filePath = filePath;
	}

	@Override
	public byte[] prepareContent() throws IOException {

		// 读取指定的文件
		BufferedInputStream fileInputStream = new BufferedInputStream( new FileInputStream( new File(
				filePath ) ) );

		byte[] buf = new byte[BUFFER_SIZE];
		int len = 0;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		while ( ( len = fileInputStream.read( buf ) ) != -1 ) {
			bos.write( buf, 0, len );
		}
		return bos.toByteArray();
	}

	@Override
	protected void processResponse( byte[] reps ) {
		try {
			String str_resp = new String( reps, "UTF-8" );
			System.out.print( str_resp );
		}
		catch ( UnsupportedEncodingException e ) {
			// ignore
		}
	}

	// ===============================================================
	// getter / setter

	public String getFilePath() {
		return filePath;
	}
}
